package Test;

public class tickets implements Runnable {

    int tickets = 50;
    Object obj = new Object();
    @Override
    public void run() {
        while (true){
             synchronized (obj){
               //包装在需要保证安全的资源外侧
                if (tickets>0){
                    System.out.println(Thread.currentThread().getName()+"正在出售第"+tickets--+"张票");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }else{
                    System.out.println("票已售完！");
                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        // 创建实例Runnable接口类对象
        Test.tickets t = new tickets();
        // 创建多线程
        new Thread(t,"窗口1").start();
        new Thread(t,"窗口2").start();
        new Thread(t,"窗口3").start();

    }
}
